package com.itheima.aspect;

import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
//@Component
@Slf4j
public class OperateLogAspect2 {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;


    @Around("@annotation(com.itheima.aspect.Log)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long begin = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        try {
            long end = System.currentTimeMillis();
            OperateLog operateLog = new OperateLog();
            String token = request.getHeader("Token");
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id", Integer.class);
            operateLog.setOperateEmpId(id);
            operateLog.setOperateTime(LocalDateTime.now());
            operateLog.setClassName(pjp.getTarget().getClass().getName());//操作类名
            operateLog.setMethodName(pjp.getSignature().getName());//操作方法名
            operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
            operateLog.setReturnValue(proceed.toString());
            operateLog.setCostTime(end - begin);
            operateLogMapper.insert(operateLog);
        } catch (Exception e) {
            log.error("日志切面类异常");
        }

        return proceed;
    }
}
